import { FC, useCallback, useEffect, useRef, useState } from "react";
import QuestionCard from "../../../components/QuestionCard";
import styles from "./common.module.scss";
import { useDebounceFn, useRequest, useTitle } from "ahooks";
import { Empty, Spin, Typography } from "antd";
import ListSearch from "../../../components/ListSearch";
import { getQuestionListService } from "../../../services/question";
import { ResDataType } from "../../../services/ajax";
import { useSearchParams } from "react-router-dom";
import { LIST_PAGESIZE, LIST_SEARCH_PARAM_KEY } from "../../../constant";

const { Title } = Typography;

const List: FC = () => {
  useTitle("小可问卷 - 我的问卷");

  const [searchParams] = useSearchParams();
  const keyword = searchParams.get(LIST_SEARCH_PARAM_KEY) || "";
  const [started, setStarted] = useState(false); // 是否已开始加载
  const [list, setList] = useState<ResDataType[]>([]); // 全部数据
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const haveMoreData = total > list.length;
  const loadMoreRef = useRef<HTMLDivElement>(null);

  // 加载
  const { run: getQuestionList, loading } = useRequest(
    async () => {
      const data = await getQuestionListService({
        page,
        pageSize: LIST_PAGESIZE,
        keyword,
      });
      return data;
    },
    {
      manual: true,
      onSuccess(data) {
        const { list: nl = [], total = 0 } = data;
        setList(list.concat(nl));
        setTotal(total);
        setPage(page + 1);
      },
    }
  );

  // 触发加载更多
  const { run: triggerLoadMore } = useDebounceFn(
    () => {
      const elem = loadMoreRef.current;
      if (!elem) return;
      const rect = elem.getBoundingClientRect();
      if (!rect) return;
      if (rect.bottom < document.body.clientHeight) {
        getQuestionList();
        setStarted(true);
      }
    },
    { wait: 300 }
  );
  // 当页面加载，或者 url 参数 keyword 变化时，触发加载
  useEffect(() => {
    triggerLoadMore();
  }, [searchParams]);
  // 页面滚动时触发, keyword变了也要重新绑定事件
  useEffect(() => {
    if (haveMoreData) {
      window.addEventListener("scroll", triggerLoadMore);
    }

    return () => {
      window.removeEventListener("scroll", triggerLoadMore);
    };
  }, [searchParams, haveMoreData]);
  // keyword 改变后重置
  useEffect(() => {
    setStarted(false);
    setPage(1);
    setList([]);
    setTotal(0);
  }, [keyword]);

  const loadMoreContentELem = useCallback(() => {
    if (!started || loading) return <Spin />;
    if (total === 0) return <Empty description="暂无数据" />;
    if (!haveMoreData) return <span>没有更多了</span>;
    return <span>开始加载下一页</span>;
  }, [started, loading, total, haveMoreData]);

  return (
    <div>
      <div className={styles.header}>
        <div className={styles.left}>
          <Title level={3}>我的问卷</Title>
        </div>
        <div className={styles.right}>
          <ListSearch />
        </div>
      </div>
      <div className={styles.content}>
        {list.length > 0 &&
          list.map((item: any) => <QuestionCard key={item._id} {...item} />)}
      </div>
      <div className={styles.footer}>
        <div ref={loadMoreRef}>{loadMoreContentELem()}</div>
      </div>
    </div>
  );
};

export default List;
